package cbp

import groovy.xml.XmlUtil;

import javax.net.ssl.HttpsURLConnection;

class EbayService {

  static transactional = false
  def servletContext

  def getCategories() {
    // def source = loadCategoriesFromWeb()
    def source = loadCategoriesFromFile()
    assert source
      /*Scanner s = new Scanner(source)
      while (s.hasNextLine()) {
        println s.nextLine()
	    }*/
    def mediaNamespace = new groovy.xml.Namespace('urn:ebay:apis:eBLBaseComponents')
    def xml = new XmlParser().parse(source)
    // println XmlUtil.serialize(xml)
    def categories = [:]
    def rootCategoryId
    xml.CategoryArray.Category.each{categoryNode ->
      def categoryId = categoryNode.CategoryID.text()
      def parentCategoryId = categoryNode.CategoryParentID.text()
      def category = [id: categoryId, name : categoryNode.CategoryName.text()]
      categories[categoryId] = category
      def parentCategory = categories[parentCategoryId]
      if(parentCategory){
        if(!parentCategory.children){
          parentCategory.children = []
        }
        parentCategory.children << category
      }
      else{
        rootCategoryId = categoryId 
      }
    }
    categories[rootCategoryId].children
  }
  def loadCategoriesFromWeb = {
    executePost(new URL("https://api.ebay.com/ws/api.dll"),
      [
        "X-EBAY-API-COMPATIBILITY-LEVEL": "793", 
        "X-EBAY-API-DEV-NAME" : "1aff2469-23e1-4cc9-b23c-6cd0c5c5debd",
        "X-EBAY-API-APP-NAME" : "AndrewOs-dd81-4deb-8f03-60c7eb1172d3",
        "X-EBAY-API-CERT-NAME" : "514965af-0d80-45b6-9676-523c801c48fc",
        "X-EBAY-API-SITEID" : "100",
        "X-EBAY-API-CALL-NAME" : "GetCategories"
      ],
      """<?xml version="1.0" encoding="utf-8"?>
<GetCategoriesRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<RequesterCredentials>
<eBayAuthToken>AgAAAA**AQAAAA**aAAAAA**X2F2UA**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AElYCoD5iAqA6dj6x9nY+seQ**l6ABAA**AAMAAA**G7uhjIr0DGCswsc8pAIJZLRVbvNXDiPIQ5AkCY+pxv/KDRKa0tHzF6Z3728znf6ZwyYIy5ZPeGvJjV+w/6PztDI1qCX70oF+sTUAytKiTyBoRkLz6iH6L2skhPRcWteAYerh5owEa1+JZxQRcV8X1gDdT+0jJEAvGJadlBv3+dAorEGBgHDadoBEvdJk085Yp6k27XVVV89+J6gMkYTD8kuTwVPuRiXKbbqMgI2GSqVaHLhKKFnFwwwb8rglPRtB54Rr0zhdwXnBfJIBQZuhaBUsRDfBVKAb3xYTf63CNsPYSHlpeO1FFWeFwW6JojeH+7fDXwpMBS4Yx/xlNFxrigV2iftnzGh3Zom7p8wL4MiNJniOTW2emzqp3K5Ky9rWniNzrXaFJYKsNC7XaxatibL4j+5D3QtVrs6svbx2Q5aBPln7zgTHqtIuuN7k/QsCVyR/VOSMYiGiGQHvlvB0Ln/9P1HjDNDdeFt1ZJZauNowOLl2sYz3DvFG0B969NB4CMOMInOVfQY5UMtjMid4uAjZhJfuzwuiXRwmVFg5fw2sUSlYGkMc5A+KRtJ+KiN8WH4b8yWMHE5vUKOCFlTCBdd8MEwltlo2wrV74ukg1fw7Uj5tjJSYvnAn/u1048RBLD2Lp6L4zSXEeeNVeWzWVi0eA/9C12q7gGo3BhtSIfGc5r4xh/IUKtLnoIxvlBhwapnUM5tgAlBxwKqcjOTN0cXnfhvjW7m8/rJxnDsR0cPjvzXHw8sxYQrIcQcv1qNj</eBayAuthToken>
</RequesterCredentials>
<CategoryParent>6001</CategoryParent>
<LevelLimit>4</LevelLimit>
<ViewAllNodes>true</ViewAllNodes>
<DetailLevel>ReturnAll</DetailLevel>
</GetCategoriesRequest>""")
  }

  InputStream executePost(URL url, Map headers, String body){
    HttpURLConnection connection = url.openConnection()

    //set the connection to do both input and output. Request Method = POST
    connection.doInput = true
    connection.doOutput = true
    connection.requestMethod = "POST"
    connection.useCaches = false
    headers.each{key, value ->
      connection.setRequestProperty(key, value)
    }

    connection.outputStream.write(body.bytes)
    connection.connect()
    println connection.responseCode
    return connection.inputStream
  }
  def loadCategoriesFromFile = {
    //new CategoriesCache().loadCategories()
    servletContext.getResource("/WEB-INF/categories.xml").openStream()
    
  }
  def loadAveragePrice(String categoryId, int modelYear){
    def source = executePost(new URL("http://svcs.ebay.com/services/search/FindingService/v1"),
      [
        'X-EBAY-SOA-SERVICE-NAME' : 'FindingService',
        'X-EBAY-SOA-OPERATION-NAME' : 'findCompletedItems',
        'X-EBAY-SOA-SERVICE-VERSION' : '1.11.0',
        'X-EBAY-SOA-GLOBAL-ID' : 'EBAY-US',
        'X-EBAY-SOA-SECURITY-APPNAME' : 'AndrewOs-dd81-4deb-8f03-60c7eb1172d3',
        'X-EBAY-SOA-REQUEST-DATA-FORMAT' : 'XML'
      ],
      """<?xml version="1.0" encoding="utf-8"?>
<findCompletedItemsRequest xmlns="http://www.ebay.com/marketplace/search/v1/services">
  <categoryId>${categoryId}</categoryId>
  <aspectFilter>
    <aspectName>Model Year</aspectName>
    <aspectValueName>${modelYear}</aspectValueName>
  </aspectFilter>
</findCompletedItemsRequest>""")
    println "Searching by categoryId ${categoryId} and model year ${modelYear}"
    def xml = new XmlParser().parse(source)
    def mediaNamespace = new groovy.xml.Namespace('http://www.ebay.com/marketplace/search/v1/services')
    // println XmlUtil.serialize(xml)
    def items = xml.searchResult.item
    def itemCount = items.size() 
    if(!itemCount)
      return null
    double priceSum = 0
    xml.searchResult.item.each{item ->
      def price = item.sellingStatus.currentPrice.text()
      priceSum += new Double(price) 
      println item.title.text()
    }
    println "${itemCount} items found"
    return (int) priceSum / itemCount
  }
}
